﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Active.Core;

public partial class Customer_Agent : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ApplyAuthorizationRules();
        }
    }

    private void ApplyAuthorizationRules()
    {
        Agent obj = GetAgent();
        // Agent display
        if (Agent.CanEditObject())
        {
            if (obj.IsNew)
                this.AgentDetailsView.DefaultMode = DetailsViewMode.Insert;
            else
                this.AgentDetailsView.DefaultMode = DetailsViewMode.Edit;
        }
        else
        {
            this.AgentDetailsView.DefaultMode = DetailsViewMode.ReadOnly;
        }
    }

    #region BusinessObject

    private Agent GetAgent()
    {
        string idString = Request.QueryString["id"];
        object businessObj = Session["CurrentObj"];
        if (businessObj == null
            || !(businessObj is Agent)
            || (!IsPostBack && !((Agent)businessObj).Id.ToString().Equals(idString)))
        {
            try
            {
                if (!string.IsNullOrEmpty(idString))
                {
                    businessObj = Agent.GetAgent(int.Parse(idString));
                }
                else
                {
                    businessObj = Agent.NewAgent();
                }
                Session["CurrentObj"] = businessObj;
            }
            catch (System.Security.SecurityException)
            {
                Response.Redirect("~/Customer/AgentList.aspx");
            }
        }
        return businessObj as Agent;
    }

    private int SaveAgent(Agent agent)
    {
        int rowsAffected = 0;
        try
        {
            Session["CurrentObj"] = agent.Save();
            rowsAffected = 1;
        }
        catch (Csla.Validation.ValidationException ex)
        {
            throw;
        }
        catch (Csla.DataPortalException ex)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw;
        }
        return rowsAffected;
    }

    #endregion

    #region AgentDataSource

    protected void AgentDataSource_DeleteObject(object sender, Csla.Web.DeleteObjectArgs e)
    {
        try
        {
            Agent.DeleteAgent(int.Parse(e.Keys["Id"].ToString()));
            Session["currentObj"] = null;
            e.RowsAffected = 1;
        }
        catch (Csla.DataPortalException ex)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    protected void AgentDataSource_InsertObject(object sender, Csla.Web.InsertObjectArgs e)
    {
        Agent obj = GetAgent();
        Csla.Data.DataMapper.Map(e.Values, obj, true);
        e.RowsAffected = SaveAgent(obj);
    }

    protected void AgentDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
    {
        e.BusinessObject = GetAgent();
    }

    protected void AgentDataSource_UpdateObject(object sender, Csla.Web.UpdateObjectArgs e)
    {
        Agent obj = GetAgent();
        Csla.Data.DataMapper.Map(e.Values, obj);
        e.RowsAffected = SaveAgent(obj);
    }

    #endregion

    #region AgentDetailsView

    protected void AgentDetailsView_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
    {
        Agent obj = GetAgent();
        if (!obj.IsNew)
        {
            Response.Redirect("~/Customer/Agent.aspx?id=" + obj.Id.ToString(), true);
        }
    }

    protected void AgentDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {
        Label error = AgentDetailsView.FindControl("lblNameError") as Label;
        if (Agent.CheckNameIsUsed(e.Values["Name"].ToString()))
        {
            error.Text = "代理名称已存在，请重新输入。";
            e.Cancel = true;
        }
        else
        {
            error.Text = "";
        }
    }

    protected void AgentDetailsView_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
    {
        Label error = AgentDetailsView.FindControl("lblNameError") as Label;
        if (e.OldValues["Name"].ToString() != e.NewValues["Name"].ToString()
            && Agent.CheckNameIsUsed(e.NewValues["Name"].ToString()))
        {
            error.Text = "代理名称已存在，请重新输入。";
            e.Cancel = true;
        }
        else
        {
            error.Text = "";
        }
    }

    #endregion
}
